<?php

namespace Yjius\openapi\douyin;

use Yjius\common\CurlHelper;

/**
 * 抖音扫描登录-暂无账号调试-使用时注意
 * Class DouYinOauth
 * @package Yjius\openapi\douyin
 * @date  2022/7/27 9:52
 */
class DouYinOauth
{
    //应用参数
    private $client_key = null;
    private $client_secret = null;
    private $redirect_uri = null;

    //最外层初始化时，YII_ENV 可以选择不同的应用
    public function __construct($config = [])
    {
        //裁入配置
        $this->client_key = $config['client_key'] ?: '';
        $this->client_secret = $config['client_secret'] ?: '';
        $this->redirect_uri = $config['redirect_uri'] ?: '';
        if (empty($this->client_key) || empty($this->client_secret) || empty($this->redirect_uri)) {
            throw new \Exception("载入配置错误，请检查参数是否正确");
        }
    }

    /**
     * 返回【第一步：请求CODE】的url
     */
    public function getCodeUrl($state = '', $scopes = '')
    {
        $scope = !empty($scopes) ? $scopes : "video.create,video.delete,video.data,video.list,user_info,renew_refresh_token,data.external.user,data.external.item,fans.data";
        $redirectUri = urlencode($this->redirect_uri);
        $url = "https://open.douyin.com/platform/oauth/connect?client_key={$this->client_key}
        &response_type=code&scope={$scope}&redirect_uri={$redirectUri}";
        return $url;
    }

    /**
     * 第二步：通过code获取access_token
     * @param $code
     * @return bool|mixed|string
     */
    public function getAccessToken($code)
    {
        $params = [
            'code' => $code,
            'grant_type' => 'authorize_code',
            'client_key' => $this->client_key,
            'client_secret' => $this->client_secret,
        ];
        $url = 'https://open.douyin.com/oauth/access_token';
        $res = CurlHelper::httpRequest($url, [], 'GET', $params);
        return json_decode($res, true);
    }

    /**
     * 第三步：获取用户信息
     * @param string $token
     * @param string $media_id
     * @return array
     */
    public function getLoginInfo($accessToken, $openId)
    {
        $url = 'https://open.douyin.com/oauth/userinfo';
        $params['open_id'] = $openId;
        $params['access_token'] = $accessToken;
        $res = CurlHelper::httpRequest($url, [], 'GET', $params);
        return json_decode($res, true);
    }

}